package top.linyuxb.lycloud.config.starter.thread;

import lombok.Getter;
import lombok.extern.slf4j.Slf4j;
import top.linyuxb.lycloud.common.properties.LyConfigProperties;
import top.linyuxb.lycloud.config.starter.common.LyConfigService;

import java.util.concurrent.TimeUnit;

/**
 * Created by Intellij IDEA.
 *
 * @Author: linyuxb
 * @Date: 2024/6/14 14:56
 * @Desc: ly-config 配置线程
 */
@Slf4j
public class LyConfigThread {
    @Getter
    private static final LyConfigThread instance = new LyConfigThread();

    private Thread configThread;
    private volatile boolean toStop = false;

    private LyConfigThread() {}

    public void start(LyConfigProperties lyRpcClientProperties) {
        configThread = new Thread(() -> {
            while (!toStop) {
                try {
                    LyConfigService.updateValues(lyRpcClientProperties);
                } catch (Exception e) {
                    if (!toStop) {
                        log.error("LyConfigThread error", e);
                    }
                }
                try {
                    if (!toStop) {
                        TimeUnit.SECONDS.sleep(lyRpcClientProperties.getInterval());
                    }
                } catch (InterruptedException e) {
                    if (!toStop) {
                        log.warn("LyConfigThread interrupted, error", e);
                    }
                }
            }
            log.info("LyConfigThread destroy");
        });
        configThread.setDaemon(true);
        configThread.setName("ly-config LyConfigThread");
        configThread.start();
    }

    public void toStop() {
        toStop = true;
        if (configThread != null) {
            configThread.interrupt();
            try {
                configThread.join();
            } catch (InterruptedException e) {
                log.error(e.getMessage(), e);
            }
        }
    }
}
